import os

import streamlit as st

import config
import utils


@utils.exception_handler
def main():
    config.page_config("")  # 将 page_config 移动到函数开头
    name = st.query_params.get("name", default="")  # 显式指定默认值
    if name == "":
        st.title("文章列表")
        files_dict = {}
        folder_path = "./pages/base"
        # 遍历文件夹中的所有项
        file_names = [
            filename for filename in os.listdir(folder_path) if filename.endswith(".md")
        ]  # 检查是否为.md文件
        file_names.sort()  # 对文件名进行排序

        # 将排序后的文件名及其完整路径添加到字典中
        for filename in file_names:
            full_path = os.path.join(folder_path, filename)  # 获取文件的完整路径
            files_dict[filename.split(".")[0]] = full_path  # 将完整路径添加到字典中

        for filename in files_dict.keys():
            if st.button(label=f"### {filename}",use_container_width=True,type="primary"):
                st.query_params["name"] = filename
                st.rerun()
    else:
        with open(f"./pages/base/{name}.md", mode="r", encoding="utf-8") as f:
            st.markdown(f.read())
        
        
        if st.page_link("./pages/Flutter基础教程.py", label="返回文档目录", icon="📄"):
            st.query_params.clear()
            
if __name__ == "__main__":
    main()